package com.doge.calcalbum.business

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.doge.calcalbum.BuildConfig
import com.doge.calcalbum.business.calc.CalcController
import com.doge.calcalbum.business.sysalbum.SysEntryDeleteHelper
import com.doge.calcalbum.core.BaseActivity
import com.doge.calcalbum.databinding.ActivitySettingsBinding
import com.doge.calcalbum.utils.*
import com.github.iielse.switchbutton.SwitchView
import java.text.SimpleDateFormat
import java.util.*

class SettingsActivity : BaseActivity() {
    private val binding by lazy { ActivitySettingsBinding.inflate(layoutInflater) }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.version.setOnClickCallback {
            EnvHelper.switch()
        }
        binding.updatePwd.setOnClickCallback {
            CalcController.resetPwd(forceClear = false)
        }
        binding.deleteOriginSwitch.isOpened = SysEntryDeleteHelper.getState()
        binding.deleteOriginSwitch.setOnStateChangedListener(object :
            SwitchView.OnStateChangedListener {
            override fun toggleToOn(view: SwitchView?) {
                view?.toggleSwitch(true)
                SysEntryDeleteHelper.updateState(true)
            }

            override fun toggleToOff(view: SwitchView?) {
                view?.toggleSwitch(false)
                SysEntryDeleteHelper.updateState(false)
            }
        })

        val dev =
            if (BuildConfig.DEBUG) "${BuildConfig.GIT_SHA} ${formatGitTimestamp(BuildConfig.GIT_TIME)}" else ""
        binding.version.text = "v$appVersionName $dev"
    }

    private fun formatGitTimestamp(gitTime: String?): String {
        if (gitTime.isNullOrEmpty()) return ""
        // Tue Jun 15 14:18:33 2021 +0800
        return try {
            val sdf = SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy Z", Locale.UK)
            val result = sdf.parse(gitTime).time.timeDesc("MMdd_HHmm")
            log("formatGitTimestamp gitTime $gitTime result $result")
            result
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    companion object {
        fun start(context: Context) {
            context.startActivity(Intent(context, SettingsActivity::class.java).apply {
                if (context == appContext) flags = Intent.FLAG_ACTIVITY_NEW_TASK
            })
        }
    }
}